package com.xxh.myapp.controller;



import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxh.myapp.entity.*;
import com.xxh.myapp.entity.wrapper.courseWrapper;
import com.xxh.myapp.msg.Message;
import com.xxh.myapp.msg.ReturnMsg;
import com.xxh.myapp.msg.stu_info;
import com.xxh.myapp.service.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (Student)表控制层
 *
 * @author makejava
 * @since 2020-05-01 16:35:41
 */
@RestController
@RequestMapping("student")
public class StudentController extends ApiController {
    /**
     * 服务对象
     */
    @Resource
    private StudentService studentService;
    @Resource
    private DeptService deptService;
    @Resource
    private StuclService stuclService;
    @Resource
    private ScoreService scoreService;
    @Resource
    private CourseService courseService;
    @Resource
    private TeacherService teacherService;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param student 查询实体
     * @return 所有数据
     */
    @GetMapping
    public R selectAll(Page<Student> page, Student student) {
        return success(this.studentService.page(page, new QueryWrapper<>(student)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R selectOne(@PathVariable Serializable id) {
        return success(this.studentService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param student 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R insert(@RequestBody Student student) {
        return success(this.studentService.save(student));
    }

    /**
     * 修改数据
     *
     * @param student 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R update(@RequestBody Student student) {
        return success(this.studentService.updateById(student));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public R delete(@RequestParam("idList") List<Long> idList) {
        return success(this.studentService.removeByIds(idList));
    }
    //拿到学生的个人信息
    @GetMapping("/stu_info")
    public stu_info getStuInfo(int sno){
        stu_info stuInfo = new stu_info();
        //学生表信息
        Student student = studentService.getById(sno);
        //学生班级信息

        Stucl stucl = stuclService.getById(student.getClno());


        //学生所在系的信息
        Dept dept = deptService.getById(student.getMajorId());
        stuInfo.setRealName(student.getSname());
        stuInfo.setAge(student.getSage());
        stuInfo.setSex(student.getSsex());
        stuInfo.setGrade(student.getGrade());
        stuInfo.setStuClazz(stucl.getClname());
        stuInfo.setDeptName(dept.getDeptname());

        return  stuInfo;
    }

    //学生选课的接口,传入课程号与学号，执行选课操作
    //1 判断人数是否到达选课上限，若没有，cur_num（当前课程人数）+1。
    //2  成绩表插入一条记录。
    //3 传2个参数，学生学号，要选课程的课程号。
    @GetMapping("choClass")
    public ReturnMsg choClass(Integer sno, Integer cno){
        ReturnMsg msg = new ReturnMsg();

        //检查是否已经选满了
        Course course = courseService.getById(cno);
        Integer numCur = course.getStuNumCur();
        Integer numMax = course.getStuNumMax();
        //看看有没有选过这门课
        QueryWrapper<Score> wrapper = new QueryWrapper<>();
        wrapper.eq("sno",sno).eq("cno",cno);
        Score score1 = scoreService.getOne(wrapper);
        if(score1!=null){
            msg.setMsg("你已经选了这门课了");
            msg.setCode(304);
            return msg;
        }else {
            if(numCur.equals(numMax)){
                msg.setCode(Message.MAX_COURSE_NUM.getCode());
                msg.setMsg(Message.MAX_COURSE_NUM.getMsg());
                return  msg;
            }else {
                course.setStuNumCur(course.getStuNumCur()+1);//课程已选人数+1
                courseService.updateById(course);//更新课程表
                Score score = new Score();
                //不能设成绩，因为老师还没改分数；
                score.setSno(sno);
                score.setCno(cno);
                scoreService.save(score);//成绩表插入一条记录
                msg.setCode(Message.SUCCESS_CHOOSE_COURSE.getCode());
                msg.setMsg(Message.SUCCESS_CHOOSE_COURSE.getMsg());
                return msg;
            }
        }
    }

    //学生退课的接口
    //1 看看学生有没有选课
    //2 退课，删除成绩表的记录,当前课程的选课人数-1
    @PostMapping("dropClass")
    public  ReturnMsg dropClass(int sno, int cno){
        ReturnMsg msg = new ReturnMsg();
        QueryWrapper<Score> wrapper = new QueryWrapper<>();
        wrapper.eq("sno",sno).eq("cno",cno);
        Score score = scoreService.getOne(wrapper);
        if(score==null){
            msg.setMsg(Message.CANT_DROP.getMsg());
            msg.setCode(Message.CANT_DROP.getCode());
            return msg;
        }else {
            scoreService.remove(wrapper);
            Course course = courseService.getById(cno);
            course.setStuNumCur(course.getStuNumCur()-1);
            courseService.updateById(course);//选修人数-1
            msg.setCode(Message.SUCCESS_DROP_COURSE.getCode());
            msg.setMsg(Message.SUCCESS_DROP_COURSE.getMsg());
            return msg;
        }
    }


    //学生查看已选课程，查询成绩表，条件：成绩为-1，学号=学号
    @GetMapping("mycourse")
    public HashMap<String, List<courseWrapper>> checkMyCourse(int sno){
        QueryWrapper<Score> wrapper = new QueryWrapper<>();
        wrapper.eq("sno",sno).eq("grade",-1);
        List<Score> scores = scoreService.list(wrapper);
        //拿到已选课程的id列表
        List<Integer>cnoList =new ArrayList<>();
        for (Score score:scores){
            cnoList.add(score.getCno());
        }
        //构建查询条件，返回已选的课程信息
        QueryWrapper<Course> coqueryWrapper = new QueryWrapper<>();
        if(cnoList.size()>0){
            coqueryWrapper.in("cno",cnoList);
        }else {
            //刚入学学生，没有已选课程
            coqueryWrapper.in("cno",-1);
        }
        List<Course> courseList = courseService.list(coqueryWrapper);
        List<courseWrapper> wrapcourseList = new ArrayList<>();
        for(Course c:courseList){
            courseWrapper courseWrapper = new courseWrapper();
            Course course=(Course)c.clone();
            courseWrapper.setCourse(course);
            //得到系
            Dept dept = deptService.getById(course.getMajorId());
            //得到老师
            Teacher teacher = teacherService.getById(course.getTno());
            //包装类丰富所需信息
            courseWrapper.setDepName(dept.getDeptname());
            courseWrapper.setTeaName(teacher.getTname());
            //包装类请求按钮名称
            courseWrapper.setBtnRequestName("退课按钮");
            wrapcourseList.add(courseWrapper);
        }
        HashMap<String, List<courseWrapper>> ListHashMap = new HashMap<>();
        ListHashMap.put("mylist",wrapcourseList);
        return  ListHashMap;
    }

    //学生请求 选课信息的接口，返回可以选的课程
    //什么叫可以选择的课程？就是拿出选课表中没有的记录。
    @GetMapping("canchocourse")
    public HashMap<String, List<courseWrapper>> getCanChooseCourse(int sno){
        QueryWrapper<Score> scoreQueryWrapper = new QueryWrapper<>();
        scoreQueryWrapper.eq("sno",sno);
        //已选课程
        List<Score> scores = scoreService.list(scoreQueryWrapper);
        List<Integer>cnoList =new ArrayList<>();
        //拿到已选课程的id列表
        for (Score score:scores){
            cnoList.add(score.getCno());
        }
        //构建查询条件，返回的没有选的课程
        QueryWrapper<Course> coqueryWrapper = new QueryWrapper<>();
        if(cnoList.size()>0){
            coqueryWrapper.notIn("cno",cnoList);
        }else {
            //刚入学学生，没有已选课程
            coqueryWrapper.notIn("cno",-1);
        }

        List<Course> courseList = courseService.list(coqueryWrapper);
        List<courseWrapper> wrapcourseList = new ArrayList<>();
        for(Course c:courseList){
            courseWrapper courseWrapper = new courseWrapper();
            Course course=(Course)c.clone();
            courseWrapper.setCourse(course);
            //得到系
            Dept dept = deptService.getById(course.getMajorId());
            //得到老师
            Teacher teacher = teacherService.getById(course.getTno());
            //包装类丰富所需信息
            courseWrapper.setDepName(dept.getDeptname());
            courseWrapper.setTeaName(teacher.getTname());
            //包装类请求按钮名称
            courseWrapper.setBtnRequestName("选课按钮");
            wrapcourseList.add(courseWrapper);
        }
        HashMap<String, List<courseWrapper>> ListHashMap = new HashMap<>();
        ListHashMap.put("mylist",wrapcourseList);
        return ListHashMap;
    }



}